<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" ref="dialogFormRef" label-width="100px" label-position="left">
            <template v-if="mode=='modify'">
                <el-form-item :label="$t('user.table.username')" prop="username">
                    <el-input v-model="form.username" disabled clearable></el-input>
                </el-form-item>
                <el-form-item :label="$t('user.table.oldPassword')" prop="password">
                    <el-input type="password" v-model="form.password" :placeholder="$t('user.table.oldPasswordPlaceholder')" clearable show-password></el-input>
                </el-form-item>
            </template>
            <el-form-item :label="$t('user.table.newPassword')" prop="newpassword">
                <el-input type="password" v-model="form.newpassword" :placeholder="$t('user.table.newPasswordPlaceholder')" clearable show-password></el-input>
            </el-form-item>
            <el-form-item :label="$t('user.table.confirmPassword')" prop="repassword">
                <el-input type="password" v-model="form.repassword" :placeholder="$t('user.table.confirmPasswordPlaceholder')" clearable show-password></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
			<el-button @click="visible=false">{{ $t('common.cancel') }}</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">{{ $t('common.save') }}</el-button>
		</template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, inject, computed } from 'vue';
import api from '@/api';
import i18n from '@/locales';
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from 'vue-router';

// 获取全局注入的工具对象和路由实例
const $TOOL = inject('$TOOL');
const router = useRouter();

// 定义用于发射方法
const emit = defineEmits(['success', 'closed']);
// 定义响应式数据
const mode = ref('modify');
const dialogFormRef = ref(null);
const titleMap = reactive({
    modify:  i18n.global.t('common.modify') + i18n.global.t('user.password'),
    reset :  i18n.global.t('common.reset')  + i18n.global.t('user.password'),
});
const visible = ref(false);
const isSaveing = ref(false);
const form = reactive({
    username: "",
    password: "",
    newpassword: "",
    repassword: "",
    ids: [],
});
const rules = computed(() => ({
    username: [{ required: true, message: i18n.global.t('user.usernameRulePlaceholder') }],
    password: [ { required: true, message: i18n.global.t('user.passwordRulePlaceholder') }],
    newpassword: [
        { required: true, message: i18n.global.t('user.passwordRulePlaceholder') },
        { validator: (rule, value, callback) => {
            if (value !== form.password) {
                dialogFormRef.value.validateField('repassword');
            }
            callback();
        }}
    ],
    repassword: [
        { required: true, message: i18n.global.t('user.password2RulePlaceholder') },
        { validator: (rule, value, callback) => {
            if (value !== form.newpassword) {
                callback(new Error(i18n.global.t('user.confirmRulePlaceholder')));
            } else {
                callback();
            }
        }}
    ],
}));
// 自定义显示的方法
const open = (newMode = 'add', ids) => {
    mode.value = newMode;
    form.ids = ids;
    visible.value = true;
};// 自定义提交表单的方法
const submit = () => {
    dialogFormRef.value.validate(async (valid) => {
        if (valid) {
            isSaveing.value = true;
            try {
                const res = await api.setting.user.reset.post(form);
                if (res.code == 200) {
                    emit('success', form);
                    visible.value = false;
                    if (form.ids && form.ids.includes($TOOL.data.get("USER_INFO").id)) {
                        ElMessageBox.confirm(i18n.global.t('userbar.reLogin'), i18n.global.t('common.tip'), {
                            type: 'warning',
                            center: true,
                        }).then(() => {
                            router.push({ path: "/login" });
                        });
                    } else {
                        ElMessage.success(res.message);
                    }
                } else {
                    ElMessage.error(res.message);
                }
            } catch (error) {
                console.error('Error in setting/user/password/submit action:', error);
            } finally {
                isSaveing.value = false;
            }
        }
    });
};
// 自定义表单注入数据的方法
const setData = (data) => {
    form.ids = [data.id];
    form.username = data.username;
};
defineExpose({open, setData});
</script>